// pages/djs.js
Page({
    /**
     * 组件的初始数据
     */
    data: {
        countdowns: [
            {id: 1, title: '平安夜',day: '2024-12-24T00:00:00', countdown: ''},
            {id: 2, title: '圣诞节',day: '2024-12-25T00:00:00', countdown: ''},
            {id: 3, title: '元旦',day: '2025-01-01T00:00:00', countdown: ''},
            {id: 4, title: '回家',day: '2025-01-22T00:00:00', countdown: ''},
            {id: 5, title: '除夕',day: '2025-01-28T00:00:00', countdown: ''},
            {id: 6, title: '春节',day: '2025-01-29T00:00:00', countdown: ''},
            {id: 7, title: '清明节',day: '2025-04-04T00:00:00', countdown: ''},
            {id: 8, title: '劳动节',day: '2025-05-01T00:00:00', countdown: ''},
            {id: 9, title: '端午节',day: '2025-05-31T00:00:00', countdown: ''},
            {id: 10, title: '国庆节',day: '2025-10-01T00:00:00', countdown: ''},
            {id: 11, title: '中秋节',day: '2025-10-06T00:00:00', countdown: ''},
        ],
    },
    onLoad() {
        // 页面加载时开始倒计时
        this.updateCountdowns();
        this.timer = setInterval(() => {
            this.updateCountdowns();
        }, 1000); 
    },
    // 页面销毁时执行
    onUnload() {
        // 页面卸载时，清除定时器
        clearInterval(this.timer);
    },
    // 更新倒计时并过滤已过期数据
    updateCountdowns() {
        const now = new Date();
        const updatedCountdowns = this.data.countdowns
        .filter(item => new Date(item.day) > now) // 过滤未过期的倒计时
        .map(item => {
            const diff = new Date(item.day) - now;
            item.countdown = this.formatCountdown(diff); // 更新倒计时
            return item;
        });

        this.setData({
        countdowns: updatedCountdowns,
        });
    },
    padZero(value) {
        return value < 10 ? '0' + value : value;
    },
    // 格式化倒计时（将毫秒转为天、小时、分钟、秒）
    formatCountdown(ms) {
        const days = Math.floor(ms / (1000 * 60 * 60 * 24));
        const hours = Math.floor((ms % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((ms % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((ms % (1000 * 60)) / 1000);
        return `${this.padZero(days)}天 ${this.padZero(hours)}小时 ${this.padZero(minutes)}分钟 ${this.padZero(seconds)}秒`;
    },
    // 返回
    pageBack() {
        wx.navigateBack({
            delta: 1
        });
    }
})